import { io } from 'socket.io-client';

class WebRTCService {
  constructor(serverUrl) {
    console.log('WebRTCService: 初始化，连接到服务器:', serverUrl);

    // 连接到信令服务器
    this.socket = io(serverUrl, {
      reconnectionDelayMax: 10000,
      reconnection: true,
      reconnectionAttempts: 10
    });

    this.socket.on('connect', () => {
      console.log('WebRTCService: 已连接到信令服务器，Socket ID:', this.socket.id);
    });

    this.socket.on('connect_error', (error) => {
      console.error('WebRTCService: 连接到信令服务器失败:', error);
      if (this.listeners.error) {
        this.listeners.error(`连接到信令服务器失败: ${error.message}`);
      }
    });

    this.roomId = null;
    this.userId = this.generateId();
    this.localStream = null;
    this.peerConnections = {};
    this.pendingIceCandidates = {};
    this.listeners = {
      userConnected: null,
      userDisconnected: null,
      userStartedSharing: null,
      userStoppedSharing: null,
      streamReceived: null,
      roomCreated: null,
      roomList: null,
      error: null
    };

    this.setupSocketListeners();
  }

  // 生成随机ID
  generateId() {
    return Math.random().toString(36).substr(2, 9);
  }

  // 设置事件监听器
  on(event, callback) {
    if (event in this.listeners) {
      this.listeners[event] = callback;
    }
  }

  // 移除事件监听器
  off(event, callback) {
    if (event in this.listeners && this.listeners[event] === callback) {
      this.listeners[event] = null;
    }
  }

  // 获取房间列表
  getRoomList() {
    console.log('WebRTCService: 请求房间列表');
    this.socket.emit('get-room-list');
  }

  // 创建房间
  createRoom() {
    this.roomId = this.generateId();
    console.log('WebRTCService: 创建房间:', this.roomId);
    this.socket.emit('join-room', this.roomId, this.userId);

    if (this.listeners.roomCreated) {
      this.listeners.roomCreated(this.roomId);
    }

    return this.roomId;
  }

  // 加入房间
  joinRoom(roomId) {
    this.roomId = roomId;
    console.log('WebRTCService: 加入房间:', roomId);
    this.socket.emit('join-room', roomId, this.userId);

    // 加入房间后立即请求获取房间内的用户列表
    // 这有助于识别当前正在共享屏幕的用户
    setTimeout(() => {
      if (this.roomId) {
        console.log('WebRTCService: 请求房间用户列表');
        this.socket.emit('get-room-users', this.roomId);
      }
    }, 500); // 短暂延迟以确保join-room事件已处理
  }

  // 离开房间
  leaveRoom() {
    if (this.roomId) {
      console.log('WebRTCService: 离开房间:', this.roomId);
      this.socket.emit('leave-room', this.roomId, this.userId);
      this.roomId = null;

      // 如果有本地流，停止共享
      if (this.localStream) {
        this.stopSharing();
      }

      // 关闭所有对等连接
      Object.values(this.peerConnections).forEach(pc => pc.close());
      this.peerConnections = {};
    }
  }

  // 开始屏幕共享
  async startSharing(providedStream = null) {
    try {
      // 确保在有效房间中才允许共享
      if (!this.roomId) {
        console.error('WebRTCService: 无法共享屏幕，房间ID为空');
        if (this.listeners.error) {
          this.listeners.error(`无法共享屏幕: 请先加入或创建房间`);
        }
        throw new Error('请先加入或创建房间，然后再共享屏幕');
      }

      console.log('WebRTCService: 开始屏幕共享，房间ID:', this.roomId);

      // 使用提供的流或获取新的屏幕共享流
      if (providedStream) {
        console.log('WebRTCService: 使用提供的媒体流');
        this.localStream = providedStream;
      } else {
        // 获取屏幕共享流
        console.log('WebRTCService: 请求新的屏幕共享流');
        this.localStream = await navigator.mediaDevices.getDisplayMedia({
          video: {
            cursor: 'always',
            displaySurface: 'monitor'
          },
          audio: false
        });
      }

      console.log('WebRTCService: 获取到屏幕共享流:', this.localStream);
      console.log('WebRTCService: 当前房间ID:', this.roomId);

      // 通知服务器我们开始共享
      this.socket.emit('start-sharing', this.roomId, this.userId);

      // 为房间内的每个其他用户创建对等连接
      // 这确保了在开始共享后立即建立连接
      if (this.roomId) {
        this.socket.emit('get-room-users', this.roomId);
      }

      // 监听流停止事件
      this.localStream.getVideoTracks()[0].addEventListener('ended', () => {
        console.log('WebRTCService: 用户停止了屏幕共享');
        this.stopSharing();
      });

      return this.localStream;

    } catch (error) {
      console.error('WebRTCService: 获取屏幕共享失败:', error);
      if (this.listeners.error) {
        this.listeners.error(`获取屏幕共享失败: ${error.message}`);
      }
      throw error;
    }
  }

  // 停止屏幕共享
  stopSharing() {
    if (this.localStream) {
      console.log('WebRTCService: 停止屏幕共享');
      this.localStream.getTracks().forEach(track => track.stop());
      this.localStream = null;

      // 通知服务器我们停止共享
      this.socket.emit('stop-sharing', this.roomId, this.userId);

      // 关闭所有对等连接
      Object.values(this.peerConnections).forEach(pc => pc.close());
      this.peerConnections = {};
    }
  }

  // 创建对等连接并发送提议
  async createPeerConnection(targetUserId) {
    console.log('WebRTCService: 创建对等连接到用户:', targetUserId);

    // 如果已存在此连接，则先关闭
    if (this.peerConnections[targetUserId]) {
      console.log('WebRTCService: 已存在连接，关闭旧连接');
      this.peerConnections[targetUserId].close();
    }

    // 创建新的RTCPeerConnection实例
    const iceServers = [
      // { urls: 'stun:stun.xten.com:3478' },
      { urls: 'stun:stun1.l.google.com:19302' },
      { urls: 'stun:stun2.l.google.com:19302' },
      { urls: 'stun:stun3.l.google.com:19302' },
      { urls: 'stun:stun4.l.google.com:19302' },
      // // 添加免费的公共TURN服务器
      {
        urls: 'turn:openrelay.metered.ca:80',
        username: 'openrelayproject',
        credential: 'openrelayproject'
      },
      {
        urls: 'turn:openrelay.metered.ca:443',
        username: 'openrelayproject',
        credential: 'openrelayproject'
      },
      {
        urls: 'turn:openrelay.metered.ca:443?transport=tcp',
        username: 'openrelayproject',
        credential: 'openrelayproject'
      }
    ];

    console.log('WebRTCService: 使用ICE服务器:', iceServers);

    const pc = new RTCPeerConnection({
      iceServers: iceServers,
      iceTransportPolicy: 'all',
      iceCandidatePoolSize: 10
    });

    this.peerConnections[targetUserId] = pc;

    // 监听连接状态变化
    pc.onconnectionstatechange = (event) => {
      console.log(`WebRTCService: 连接状态变化 (${targetUserId}):`, pc.connectionState);
    };

    // 监听ICE连接状态变化
    pc.oniceconnectionstatechange = (event) => {
      console.log(`WebRTCService: ICE连接状态变化 (${targetUserId}):`, pc.iceConnectionState);

      // 如果连接失败或断开，尝试重新连接
      if (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'disconnected') {
        console.log('WebRTCService: ICE连接失败，尝试重新协商');
        // 在短暂延迟后尝试重新协商连接
        setTimeout(() => {
          this.restartIce(targetUserId);
        }, 2000);
      }
    };

    // 添加本地流
    if (this.localStream) {
      console.log('WebRTCService: 添加本地流到连接');
      this.localStream.getTracks().forEach(track => {
        pc.addTrack(track, this.localStream);
      });
    }

    // 处理ICE候选
    pc.onicecandidate = (event) => {
      if (event.candidate) {
        console.log(`WebRTCService: 发送ICE候选到 ${targetUserId}:`, event.candidate);
        this.socket.emit('ice-candidate', this.roomId, this.userId, {
          targetUserId: targetUserId,
          candidate: event.candidate
        });
      } else {
        console.log('WebRTCService: ICE候选收集完成');
      }
    };

    // 创建提议
    try {
      console.log('WebRTCService: 创建提议');
      const offer = await pc.createOffer({
        offerToReceiveAudio: false,
        offerToReceiveVideo: true
      });

      console.log('WebRTCService: 设置本地描述');
      await pc.setLocalDescription(offer);

      console.log('WebRTCService: 发送提议到:', targetUserId);
      this.socket.emit('offer', this.roomId, this.userId, {
        targetUserId: targetUserId,
        offer: offer
      });

    } catch (error) {
      console.error('WebRTCService: 创建提议失败:', error);
      if (this.listeners.error) {
        this.listeners.error(`创建提议失败: ${error.message}`);
      }
    }

    return pc;
  }

  // 处理接收到的提议
  async handleOffer(senderId, offerData) {
    if (offerData.targetUserId !== this.userId) return;

    console.log('WebRTCService: 收到提议:', senderId, offerData);

    try {
      // 检查是否已存在此连接
      let pc = this.peerConnections[senderId];

      // 如果连接存在但处于非稳定状态，可能需要重置
      if (pc && pc.signalingState !== 'stable') {
        console.warn(`WebRTCService: 收到offer时连接状态非稳定: ${pc.signalingState}，尝试重置连接`);
        pc.close();
        delete this.peerConnections[senderId];
        pc = null;
      }

      // 创建新的RTCPeerConnection实例
      if (!pc) {
        const iceServers = [
          { urls: 'stun:stun.l.google.com:19302' },
          { urls: 'stun:stun1.l.google.com:19302' },
          { urls: 'stun:stun2.l.google.com:19302' },
          { urls: 'stun:stun3.l.google.com:19302' },
          { urls: 'stun:stun4.l.google.com:19302' },
          // 添加免费的公共TURN服务器
          {
            urls: 'turn:openrelay.metered.ca:80',
            username: 'openrelayproject',
            credential: 'openrelayproject'
          },
          {
            urls: 'turn:openrelay.metered.ca:443',
            username: 'openrelayproject',
            credential: 'openrelayproject'
          },
          {
            urls: 'turn:openrelay.metered.ca:443?transport=tcp',
            username: 'openrelayproject',
            credential: 'openrelayproject'
          }
        ];

        console.log('WebRTCService: 创建新的对等连接');
        pc = new RTCPeerConnection({
          iceServers: iceServers,
          iceTransportPolicy: 'all',
          iceCandidatePoolSize: 10
        });

        this.peerConnections[senderId] = pc;

        // 监听连接状态变化
        pc.onconnectionstatechange = (event) => {
          console.log(`WebRTCService: 连接状态变化 (${senderId}):`, pc.connectionState);
        };

        // 监听ICE连接状态变化
        pc.oniceconnectionstatechange = (event) => {
          console.log(`WebRTCService: ICE连接状态变化 (${senderId}):`, pc.iceConnectionState);

          // 如果连接失败或断开，尝试重新连接
          if (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'disconnected') {
            console.log('WebRTCService: ICE连接失败，尝试重新协商');
            // 在短暂延迟后尝试重新协商连接
            setTimeout(() => {
              this.restartIce(senderId);
            }, 2000);
          }
        };

        // 处理ICE候选
        pc.onicecandidate = (event) => {
          if (event.candidate) {
            console.log(`WebRTCService: 发送ICE候选到 ${senderId}:`, event.candidate);
            this.socket.emit('ice-candidate', this.roomId, this.userId, {
              targetUserId: senderId,
              candidate: event.candidate
            });
          }
        };

        // 处理接收到的流
        pc.ontrack = (event) => {
          console.log('WebRTCService: 接收到远程流:', event.streams[0]);

          if (this.listeners.streamReceived) {
            this.listeners.streamReceived(event.streams[0]);
          }
        };
      }

      // 确保连接处于稳定状态
      if (pc.signalingState !== 'stable') {
        console.warn(`WebRTCService: 连接非稳定状态 (${pc.signalingState})，尝试回滚`);
        await Promise.all([
          pc.setLocalDescription({type: "rollback"}),
          pc.setRemoteDescription(new RTCSessionDescription(offerData.offer))
        ]);
      } else {
        // 设置远程描述
        console.log('WebRTCService: 设置远程描述，当前信令状态:', pc.signalingState);
        await pc.setRemoteDescription(new RTCSessionDescription(offerData.offer));
      }

      // 应用之前缓存的ICE候选
      this.applyPendingIceCandidates(senderId);

      // 创建应答
      console.log('WebRTCService: 创建应答');
      const answer = await pc.createAnswer();

      console.log('WebRTCService: 设置本地描述');
      await pc.setLocalDescription(answer);

      console.log('WebRTCService: 发送应答到:', senderId);
      this.socket.emit('answer', this.roomId, this.userId, {
        targetUserId: senderId,
        answer: answer
      });

    } catch (error) {
      console.error('WebRTCService: 处理提议失败:', error);
      if (this.listeners.error) {
        this.listeners.error(`处理提议失败: ${error.message}`);
      }
    }
  }

  // 处理接收到的应答
  async handleAnswer(senderId, answerData) {
    if (answerData.targetUserId !== this.userId) return;

    console.log('WebRTCService: 收到应答:', senderId, answerData);

    const pc = this.peerConnections[senderId];
    if (pc) {
      try {
        // 检查连接的信令状态，只有在have-local-offer状态才能设置远程应答
        if (pc.signalingState !== 'have-local-offer') {
          console.warn(`WebRTCService: 无法设置远程描述，当前信令状态不正确: ${pc.signalingState}`);
          console.log('WebRTCService: 尝试重新协商连接');
          // 如果我们有本地流且不处于正确状态，尝试创建新的offer
          if (this.localStream) {
            await this.restartIce(senderId);
          }
          return;
        }

        console.log('WebRTCService: 设置远程描述，当前信令状态:', pc.signalingState);
        await pc.setRemoteDescription(new RTCSessionDescription(answerData.answer));
        console.log('WebRTCService: 完成连接建立，新的信令状态:', pc.signalingState);

        // 应用之前缓存的ICE候选
        this.applyPendingIceCandidates(senderId);
      } catch (error) {
        console.error('WebRTCService: 设置远程描述失败:', error);
        if (this.listeners.error) {
          this.listeners.error(`设置远程描述失败: ${error.message}`);
        }
      }
    } else {
      console.error('WebRTCService: 未找到对应的PeerConnection:', senderId);
    }
  }

  // 处理ICE候选
  handleIceCandidate(senderId, candidateData) {
    if (candidateData.targetUserId !== this.userId) return;

    console.log('WebRTCService: 收到ICE候选:', senderId, candidateData);

    const pc = this.peerConnections[senderId];
    if (pc) {
      try {
        if (pc.remoteDescription) {
          console.log('WebRTCService: 添加ICE候选');
          pc.addIceCandidate(new RTCIceCandidate(candidateData.candidate))
            .catch(error => {
              console.error('WebRTCService: 添加ICE候选失败:', error);
            });
        } else {
          console.log('WebRTCService: 延迟添加ICE候选，等待远程描述');
          // 缓存ICE候选
          if (!this.pendingIceCandidates[senderId]) {
            this.pendingIceCandidates[senderId] = [];
          }
          this.pendingIceCandidates[senderId].push(candidateData.candidate);
        }
      } catch (error) {
        console.error('WebRTCService: 添加ICE候选失败:', error);
        if (this.listeners.error) {
          this.listeners.error(`添加ICE候选失败: ${error.message}`);
        }
      }
    } else {
      console.error('WebRTCService: 未找到对应的PeerConnection:', senderId);
    }
  }

  // 应用缓存的ICE候选
  applyPendingIceCandidates(userId) {
    const pc = this.peerConnections[userId];
    const candidates = this.pendingIceCandidates[userId] || [];

    if (pc && pc.remoteDescription && candidates.length > 0) {
      console.log(`WebRTCService: 应用 ${candidates.length} 个缓存的ICE候选给用户 ${userId}`);

      candidates.forEach(candidate => {
        pc.addIceCandidate(new RTCIceCandidate(candidate))
          .catch(error => {
            console.error('WebRTCService: 添加缓存的ICE候选失败:', error);
          });
      });

      // 清空缓存
      this.pendingIceCandidates[userId] = [];
    }
  }

  // 重启ICE连接
  async restartIce(userId) {
    console.log(`WebRTCService: 尝试重启与 ${userId} 的ICE连接`);
    const pc = this.peerConnections[userId];

    if (!pc) {
      console.error(`WebRTCService: 未找到与 ${userId} 的对等连接`);
      return;
    }

    try {
      // 记录当前连接状态
      console.log(`WebRTCService: 当前连接状态 - 连接: ${pc.connectionState}, ICE: ${pc.iceConnectionState}, 信令: ${pc.signalingState}`);

      // 根据不同的信令状态采取不同的处理策略
      if (pc.signalingState === 'stable') {
        // 在稳定状态，我们可以创建新的offer
        console.log('WebRTCService: 连接处于稳定状态，创建新的offer');
        // 创建重启ICE的新offer
        const offer = await pc.createOffer({
          iceRestart: true,
          offerToReceiveAudio: false,
          offerToReceiveVideo: true
        });

        // 设置本地描述
        await pc.setLocalDescription(offer);

        // 发送新的提议
        this.socket.emit('offer', this.roomId, this.userId, {
          targetUserId: userId,
          offer: offer
        });
      } else if (pc.signalingState === 'have-local-offer' || pc.signalingState === 'have-remote-offer') {
        // 如果已经有一个offer在进行中，我们需要重置连接
        console.log(`WebRTCService: 连接处于非稳定状态 (${pc.signalingState})，需要重置连接`);

        // 关闭并重新创建连接
        pc.close();
        delete this.peerConnections[userId];

        // 如果我们是共享方，创建新的连接
        if (this.localStream) {
          console.log('WebRTCService: 我们是共享方，重新创建连接');
          this.createPeerConnection(userId);
        } else {
          console.log('WebRTCService: 我们是观看方，等待共享方重新创建连接');
          // 观看方无需主动创建连接，等待共享方发起
        }
      } else {
        // 其他状态（closed等）
        console.log(`WebRTCService: 连接处于其他状态 (${pc.signalingState})，重置连接`);

        // 关闭并重新创建连接
        pc.close();
        delete this.peerConnections[userId];

        // 如果我们是共享方，重新创建连接
        if (this.localStream) {
          console.log('WebRTCService: 我们是共享方，重新创建连接');
          this.createPeerConnection(userId);
        }
      }
    } catch (error) {
      console.error('WebRTCService: 重启ICE失败:', error);

      // 尝试完全重建连接
      console.log('WebRTCService: 重启失败，尝试完全重建连接');
      try {
        pc.close();
      } catch (e) {
        console.error('WebRTCService: 关闭连接出错:', e);
      }

      delete this.peerConnections[userId];

      // 如果我们是共享方，创建新的连接
      if (this.localStream) {
        console.log('WebRTCService: 我们是共享方，重新创建连接');
        this.createPeerConnection(userId);
      }
    }
  }

  // 设置Socket.io事件监听器
  setupSocketListeners() {
    // 房间列表
    this.socket.on('room-list', (roomList) => {
      console.log('WebRTCService: 收到房间列表:', roomList);
      if (this.listeners.roomList) {
        this.listeners.roomList(roomList);
      }
    });

    // 收到房间用户列表
    this.socket.on('room-users', (roomId, userIds) => {
      console.log(`WebRTCService: 收到房间 ${roomId} 的用户列表:`, userIds);

      // 如果我们正在共享屏幕，需要为每个用户创建连接
      if (this.localStream && userIds && userIds.length > 0) {
        console.log('WebRTCService: 检测到需要连接的用户，创建对等连接');
        userIds.forEach(userId => {
          this.createPeerConnection(userId);
        });
      }
    });

    // 用户连接
    this.socket.on('user-connected', (newUserId) => {
      console.log('WebRTCService: 用户已连接:', newUserId);

      if (this.listeners.userConnected) {
        this.listeners.userConnected(newUserId);
      }

      // 如果我们正在共享屏幕，为新用户创建对等连接
      if (this.localStream) {
        console.log('WebRTCService: 有新用户加入，创建对等连接');
        this.createPeerConnection(newUserId);
      }
    });

    // 用户断开连接
    this.socket.on('user-disconnected', (disconnectedUserId) => {
      console.log('WebRTCService: 用户已断开连接:', disconnectedUserId);

      if (this.listeners.userDisconnected) {
        this.listeners.userDisconnected(disconnectedUserId);
      }

      // 清理对应的对等连接
      if (this.peerConnections[disconnectedUserId]) {
        this.peerConnections[disconnectedUserId].close();
        delete this.peerConnections[disconnectedUserId];
      }
    });

    // 用户开始屏幕共享
    this.socket.on('user-started-sharing', (sharingUserId) => {
      console.log('WebRTCService: 用户开始共享屏幕:', sharingUserId);

      if (this.listeners.userStartedSharing) {
        this.listeners.userStartedSharing(sharingUserId);
      }

      // 如果收到共享通知，主动创建与共享方的对等连接
      // 这确保重新加入房间的用户能够连接到已经在共享的用户
      if (sharingUserId !== this.userId) {
        console.log('WebRTCService: 收到共享通知，创建与共享方的对等连接');
        // 请求房间内的用户列表，确保能获取到正确的用户ID
        this.socket.emit('get-room-users', this.roomId);
        // 直接创建与共享方的连接
        this.createPeerConnection(sharingUserId);
      }
    });

    // 用户停止屏幕共享
    this.socket.on('user-stopped-sharing', (sharingUserId) => {
      console.log('WebRTCService: 用户停止共享屏幕:', sharingUserId);

      if (this.listeners.userStoppedSharing) {
        this.listeners.userStoppedSharing(sharingUserId);
      }
    });

    // WebRTC信令
    this.socket.on('offer', (senderId, offerData) => {
      this.handleOffer(senderId, offerData);
    });

    this.socket.on('answer', (senderId, answerData) => {
      this.handleAnswer(senderId, answerData);
    });

    this.socket.on('ice-candidate', (senderId, candidateData) => {
      this.handleIceCandidate(senderId, candidateData);
    });
  }

  // 检查房间状态
  checkRoomState() {
    console.log('WebRTCService: 检查房间状态');
    console.log('- 房间ID:', this.roomId);
    console.log('- Socket 连接状态:', this.socket ? (this.socket.connected ? '已连接' : '未连接') : '未初始化');
    console.log('- 用户ID:', this.userId);
    console.log('- 本地流:', this.localStream ? `存在 (${this.localStream.active ? '活跃' : '非活跃'})` : '不存在');
    console.log('- 对等连接数量:', Object.keys(this.peerConnections).length);

    // 检查每个对等连接
    if (Object.keys(this.peerConnections).length > 0) {
      console.log('- 对等连接详情:');
      Object.entries(this.peerConnections).forEach(([userId, pc]) => {
        console.log(`  - ${userId}: 连接状态=${pc.connectionState}, ICE状态=${pc.iceConnectionState}`);
      });
    }

    return {
      roomId: this.roomId,
      socketConnected: this.socket && this.socket.connected,
      userId: this.userId,
      hasLocalStream: !!this.localStream,
      peerConnectionCount: Object.keys(this.peerConnections).length
    };
  }

  // 添加一个新方法用于重新初始化房间连接
  async reinitializeRoom() {
    console.log('WebRTCService: 重新初始化房间连接');

    if (!this.roomId) {
      console.error('WebRTCService: 无法重新初始化，房间ID为空');
      throw new Error('无法重新初始化，房间ID为空');
    }

    try {
      // 清理当前的连接状态
      console.log('WebRTCService: 清理当前的所有对等连接');
      const peerIds = Object.keys(this.peerConnections);

      for (const peerId of peerIds) {
        const pc = this.peerConnections[peerId];
        if (pc) {
          console.log(`WebRTCService: 关闭与 ${peerId} 的连接，当前状态: ${pc.connectionState}, 信令状态: ${pc.signalingState}`);
          try {
            pc.close();
          } catch (e) {
            console.error(`WebRTCService: 关闭连接出错:`, e);
          }
          delete this.peerConnections[peerId];
        }
      }

      // 清空待处理的ICE候选
      this.pendingIceCandidates = {};

      // 确保socket连接正常
      if (!this.socket.connected) {
        console.warn('WebRTCService: Socket未连接，尝试重新连接');
        // 等待socket重新连接
        const connectPromise = new Promise((resolve, reject) => {
          const timeout = setTimeout(() => {
            reject(new Error('Socket重连超时'));
          }, 5000);

          const connectHandler = () => {
            clearTimeout(timeout);
            resolve();
          };

          this.socket.once('connect', connectHandler);

          // 如果已经连接，直接解析
          if (this.socket.connected) {
            clearTimeout(timeout);
            this.socket.off('connect', connectHandler);
            resolve();
          }
        });

        try {
          await connectPromise;
          console.log('WebRTCService: Socket已重新连接');
        } catch (e) {
          console.error('WebRTCService: Socket重连失败:', e);
          throw new Error('Socket连接失败');
        }
      }

      // 重新请求房间用户列表
      console.log('WebRTCService: 请求房间用户列表');
      this.socket.emit('get-room-users', this.roomId);

      // 刷新房间信息
      if (this.localStream) {
        console.log('WebRTCService: 本地流存在，通知服务器我们在共享');
        this.socket.emit('start-sharing', this.roomId, this.userId);
      }

      // 返回当前房间状态
      return this.checkRoomState();
    } catch (error) {
      console.error('WebRTCService: 重新初始化房间失败:', error);
      throw error;
    }
  }
}

export default WebRTCService;
